package com.learning.javaweb_springboot_jwt.util;



import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.Claims;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import java.util.Base64;
import java.util.Date;

public class JwtUtil {

    // 使用一个固定的密钥
    private static final byte[] SECRET = Base64.getDecoder().decode("T9Z2GHfBakC74WSuRYs3ssLonX5pySA+jmY6ub5NesU=");
    private static final SecretKey KEY = new SecretKeySpec(SECRET, SignatureAlgorithm.HS256.getJcaName());
    private static final long EXPIRATION = 3600 * 1000; // 1小时

    // 生成JWT
    public static String generateToken(String username) {
        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();
    }

    // 从JWT中获取声明
    public static Claims getClaimsFromToken(String token) {
        return Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    }

    // 从JWT中获取用户名
    public static String getUsernameFromToken(String token) {
        return getClaimsFromToken(token).getSubject();
    }

    // 验证JWT
    public static boolean validateToken(String token, String username) {
        final String tokenUsername = getUsernameFromToken(token);
        return (tokenUsername.equals(username) && !isTokenExpired(token));
    }

    // 检查JWT是否过期
    public static boolean isTokenExpired(String token) {
        final Date expiration = getClaimsFromToken(token).getExpiration();
        return expiration.before(new Date());
    }


}


